﻿using MathNet.Numerics;
using SeeSharpTools.JY.ArrayUtility;
using SeeSharpTools.JY.DSP.Fundamental;
using SeeSharpTools.JY.DSP.Utility;
using Sunny.UI;
using System;
using System.Linq;

namespace SeeSharpTools.Demo
{
    public partial class FormPhase : UIPage
    {
        private bool isRunning = false;

        public FormPhase()
        {
            InitializeComponent();

            slide_NoiseAmp.Max = 0.3;
            slide_NoiseAmp.Min = 0;
            slide_NoiseAmp.Value = 0.1;

            slide_PhaseOffset.Max = 180;
            slide_PhaseOffset.Min = -180;
            slide_PhaseOffset.Value = 10;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            double sampleRate = 20000;
            double signalFreq = 50;
            double T = 10 * 1 / signalFreq;
            double[] t = Generate.LinearRange(0, 1 / sampleRate, T - 1 / sampleRate);
            double[] noise = new double[t.Length];
            Generation.UniformWhiteNoise(ref noise, slide_NoiseAmp.Value);
            double[] x = new double[t.Length];
            double[] y = new double[t.Length];
            double tau = -slide_PhaseOffset.Value; // 指定相位差，单位为度

            Generation.SineWave(ref x, 1, 0, signalFreq, sampleRate);
            Generation.SineWave(ref y, 1, tau, signalFreq, sampleRate);
            x = x.Zip(noise, (a, b) => a + b).ToArray();
            y = y.Zip(noise, (a, b) => a + b).ToArray();

            double[,] combined = new double[2, x.Length];
            ArrayManipulation.ReplaceArraySubset(x, ref combined, 0);
            ArrayManipulation.ReplaceArraySubset(y, ref combined, 1);

            easyChartX1.Plot(t, combined);
            easyChartX1.Series[0].Name = "第一个通道";
            easyChartX1.Series[1].Name = "第二个通道";

            double pd = Phase.CalPhaseShift(x, y);
            double time = pd / 360 / signalFreq;
            uiTextBox_PhaseOffset.Text = pd.ToString("f4");
            uiTextBox_TimeOffset.Text = time.ToString("f4");
        }

        private void uiSymbolButton1_Click(object sender, EventArgs e)
        {
            if (isRunning)
            {
                timer1.Stop();
                uiSymbolButton.Symbol = 61515;
                isRunning = false;
            }
            else
            {
                timer1.Start();
                uiSymbolButton.Symbol = 61516;
                isRunning = true;
            }
        }
    }
}